//
//  XDChangePasswordVerController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/3/13.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDChangePasswordVerController.h"
#import "AFHTTPSessionManager+POST.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "XDSetSafePassViewController.h"
#import "XDUserCenterController.h"
@interface XDChangePasswordVerController ()<UITextFieldDelegate,XDSetSafePassViewControllerDelegate>

@property (nonatomic, copy) NSString *smsCode;

@property (nonatomic, weak) UILabel *mobileLb;

@property (nonatomic, weak) UIButton *timeBtn;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, weak) UITextField *smsCodeField;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, weak) UIButton *nextBtn;

@end

@implementation XDChangePasswordVerController

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"修改交易密码";
    self.view.backgroundColor = kColorRGB(255, 255, 255);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"pass_Tel"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(passwordTel)];
    [self loadData];
    [self addViews];
    
}

//数据请求
- (void)loadData
{

    self.mobile = self.mobile ?  self.mobile : @"18715075382";
    NSDictionary *param =  @{@"method":@"modifySafePass",@"idNumber":self.mobile};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            
            
            
        } else {
            
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
            
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

//获取验证码
- (void)getMobileCode
{
    NSDictionary *param = @{@"method":@"getSmsCodeBySafePass"};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject)
     {
         
         if ([responseObject[@"code"] isEqualToString:@"100000"])
         {
             
             
             
             
         } else {
             [self againSMSVerify];
             [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
         }
         
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self againSMSVerify];
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"网络请求失败" view:self.view];
     }];
}
- (void)addViews
{
    UILabel *mobileLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenW-160, 40)];
    mobileLb.text = self.mobile;
    mobileLb.textColor = kColorRGB(187,147,115);
    mobileLb.font = [UIFont systemFontOfSize:22];
    mobileLb.textAlignment = NSTextAlignmentCenter;
    [mobileLb sizeToFit];
    self.mobileLb = mobileLb;
    [self.view addSubview:mobileLb];
    
    UIButton *timeBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(mobileLb.frame) + 10, 10, 70, 24)];
    timeBtn.layer.cornerRadius = 12;
    timeBtn.userInteractionEnabled = NO;
    timeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [timeBtn setTitle:@"60s" forState:UIControlStateNormal];
    [timeBtn setBackgroundColor:kColorRGB(187,147,115)];
    [timeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [timeBtn addTarget:self action:@selector(timeBtnBeClick) forControlEvents:UIControlEventTouchUpInside];
    self.timeBtn = timeBtn;
    [self.view addSubview:timeBtn];
    
    self.mobileLb.frame = CGRectMake((kScreenW - (CGRectGetMaxX(self.timeBtn.frame) - CGRectGetMinX(self.mobileLb.frame))) * 0.5, 30, self.mobileLb.frame.size.width, self.mobileLb.frame.size.height);
    self.timeBtn.frame = CGRectMake(CGRectGetMaxX(self.mobileLb.frame) + 10, 0, 70, 24);
    self.timeBtn.center = CGPointMake(self.timeBtn.center.x, self.mobileLb.center.y);
    
    self.count = 60;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerDidClick) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantPast]];
    
    UIImage *passImg = [UIImage imageNamed:@"passWord"];
    UIButton *passBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - passImg.size.width) * 0.5, CGRectGetMaxY(self.timeBtn.frame) + 20, passImg.size.width, passImg.size.height)];
    [passBtn setBackgroundImage:passImg forState:UIControlStateNormal];
    [self.view addSubview:passBtn];
    
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake((kScreenW - passImg.size.width) * 0.5, CGRectGetMaxY(self.timeBtn.frame) + 20, passImg.size.width, passImg.size.height)];
    
    textField.hidden = YES;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.delegate = self;
    [textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [textField becomeFirstResponder];
    self.smsCodeField =textField;
    [self.view addSubview:textField];
    
   
    for (int i = 0; i < 6; i++) {
        
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((kScreenW - passImg.size.width) * 0.5+i*(passImg.size.width / 6), CGRectGetMaxY(self.timeBtn.frame) + 20, passImg.size.width / 6, passImg.size.height)];
        
        
        button.titleLabel.font = [UIFont systemFontOfSize:20.0];
        
        [button addTarget:self action:@selector(touchBegin) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
        
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [self.dataSource addObject:button];
        
        [self.view addSubview:button];
        
    }
    
    
    UIImage *img = [UIImage imageNamed:@"safePass_sure_height"];
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - img.size.width) * 0.5 ,CGRectGetMaxY(self.smsCodeField.frame) + 20 , img.size.width, img.size.height)];
    [nextBtn setBackgroundImage:img forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"safePass_sure"] forState:UIControlStateDisabled];
    nextBtn.enabled = NO;
    [nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    
    self.nextBtn = nextBtn;
}
// timer
- (void)timerDidClick {
    _count -= 1;
    [_timeBtn setTitle:[NSString stringWithFormat:@"%lds", _count] forState:UIControlStateNormal];
    if (_count == 0) {
        [self againSMSVerify];
    }
}
// 验证请求失败后重新发送设置
- (void)againSMSVerify {
    _count = 60;
    _timeBtn.userInteractionEnabled = YES;
    [_timer setFireDate:[NSDate distantFuture]];
    [_timeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
}
#pragma mark -- 点击方法
- (void)timeBtnBeClick
{
    _timeBtn.userInteractionEnabled = NO;
    [_timer setFireDate:[NSDate distantPast]];
    [self getMobileCode];
}

- (void)passwordTel {
    
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"400-805-9696"];
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}

- (void)nextBtnClick:(UIButton *)nextBtn {
    
    [self requestData];
    
}

- (void)requestData {
    
    NSString *idNumber = [[self.smsCodeField.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSDictionary * param = @{@"method":@"safePassSmsCode",@"smsCode":idNumber};
    
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {

            XDSetSafePassViewController *setSafe = [[XDSetSafePassViewController alloc] init];
            setSafe.delegate = self;
            [self.navigationController pushViewController:setSafe animated:YES];
            
        }  else {
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"无网络" view:self.view];
    }];
    XDSetSafePassViewController *setSafe = [[XDSetSafePassViewController alloc] init];
    setSafe.delegate = self;
    [self.navigationController pushViewController:setSafe animated:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    NSInteger pointLength = existedLength - selectedLength + replaceLength;
    //超过6位 就不能在输入了
    if (pointLength > 6) {
        return NO;
    }else{
        return YES;
    }
    
}
- (void)touchBegin
{
    
    [self.smsCodeField becomeFirstResponder];
    
}//成为第一响应者


- (void)textFieldChange:(UITextField *)textField {
    
    NSString *text = textField.text;
    if (text.length == _dataSource.count) {
        self.nextBtn.enabled = YES;
    } else {
       self.nextBtn.enabled = NO;
    }
    
    for (int i = 0; i < _dataSource.count; i++) {
        
        
        UIButton *btn = [_dataSource objectAtIndex:i];
        
        
        NSString *str = @"";
        
        if (i < text.length) {
            
            
            str = [text substringWithRange:NSMakeRange(i, 1)];
            
            
        }
        
        [btn setTitle:str forState:UIControlStateNormal];
    }
    
    
}

- (void)sureBtnClcik:(XDSetSafePassViewController *)setSafePass {
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[XDUserCenterController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
        }
    }
}

@end
